import type { RouteRecordRaw } from 'vue-router'
import type { MenuPageVO } from '@/types/sec/menu.d'

import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/stores'
import { buildNavMenuList, buildDynamicRouteList } from '@/utils/routerUtils'

// 静态路由
const constantRouteList: RouteRecordRaw[] = [
  { path: '/login', name: 'login', component: () => import('@/pages/login/index.vue') },
  { path: '/404', name: '404', component: () => import('@/pages/404/404.vue') }
]

// 动态路由，后台返回路由数据将填充至children中
const dynamicRoute: RouteRecordRaw = {
	path: '/',
	component: () => import('@/pages/layout/index.vue'),
	redirect: '/home',
	name: '/',
	children: [
		{
			path: '/home',
			name: 'home',
			component: () => import('@/pages/home/index.vue'),
			meta: {
				title: '首页',
				affix: true
			}
		}
	]
}

// 错误路由，必须动态添加，而且要放在最后，不然容易F5刷新页面容易出现404
const errorRoute: RouteRecordRaw = {
	path: '/:pathMatch(.*)*',
	name: 'any',
	redirect: '/404'
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRouteList,
  scrollBehavior(){
    return{
      left: 0,
      top: 0
    }
  }
})

// 根据后台菜单数据初始化路由
export const initRouter = (menuList: MenuPageVO[]) => {
	// 生成Element左侧菜单导航数据
	const navMenuList = buildNavMenuList(menuList)
	store.router.setNavMenuList(navMenuList)

	// 先添加动态路由
	const dynamicRouteList = buildDynamicRouteList(navMenuList, [])
	dynamicRoute.children?.push(...dynamicRouteList)
	router.addRoute(dynamicRoute)

	// 最后添加错误路由
	router.addRoute(errorRoute)
	store.router.setRouteList(constantRouteList.concat(dynamicRoute))
}

export default router